package cat.joronya.supermanager.europeo.service;

import java.io.ByteArrayOutputStream;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.htmlcleaner.ContentNode;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.util.Log;
import cat.joronya.supermanager.europeo.Supermanager;
import cat.joronya.supermanager.europeo.market.Player;

/**
 * Recuperem el llistat de jugadors del mercat.
 * 
 * @author pol
 */
public class MarketSync extends Object//AsyncTask<String,Void,Integer>
{
	private static final String TAG = "supermanager";
	
	// el service
	private SupermanagerService service;
	
	// el client http on fer les peticions
	private DefaultHttpClient client = null;
	
	// jornada passada de loginSyn pq no es a les pagines de market
	private Integer jornada = null;
	
	// status de retorn
	public int status = -1;
	
	// market GET
	private static final String MARKET_GET = InitSync.BASE_URL+"/vermercado.php";
	// new team POST
	//private static final String NEWTEAM_POST = InitSync.BASE_URL+"/nuevoequipo.php";
	// market new team for player id GET
	//private static final String MARKET_NEWTEAM_GET = InitSync.BASE_URL+"/mercado.php";
	// day matches GET
	private static final String DAYMATCHES_GET = "http://www.acb.com/redaccion.php?id=95935";
	
	// XPATHs per treure dades de les pagines
	// players XPATH
	private static final String PLAYERS_XPATH = "//table[@background='gif/fondomercado3arriba.gif']";
	
	// comprar changes
	private static final String MARKET_BUY_GET = InitSync.BASE_URL+"/mercado.php";
	
	// nou equip
	private static final String NEW_TEAM_GET = InitSync.BASE_URL+"/nuevoequipo.php";

	// hash per guardar codi=>id_jug
	protected Hashtable<String, String> idJugPerCodi = null;
	
	// hash per guardar team vs team
	protected Hashtable<String, String> dayMatches = null;
	
	// market position for buy market parsing and postExecute
	protected String position = null;
	
	// dades extretes de les pagines
	public ArrayList<Player> guards;
	public ArrayList<Player> forwards;
	public ArrayList<Player> centers;
	public ArrayList<Player> players;
	
	/**
	 * Constructor amb el intentService que el crida.
	 * @param intentService
	 */
	public MarketSync(SupermanagerService service, DefaultHttpClient client, Integer jornada)
	{
		this.service = service;
		this.client = client;
		this.jornada = jornada;
		
		this.idJugPerCodi = new Hashtable<String, String>();
		this.dayMatches = new Hashtable<String, String>();
		
		this.guards = new ArrayList<Player>();
		this.forwards = new ArrayList<Player>();
		this.centers = new ArrayList<Player>();
	}
	
	public void deleteDayEntries()
	{
    	// primer borrem jugadors de la jornada ja que quan es dona de baixa
    	// un jugador no ha d'estar disponible al market
    	Log.d(TAG,"Deleted market data for day "+jornada.toString());
    	service.getContentResolver().delete(Supermanager.Market.CONTENT_URI,
    			Supermanager.Market.DAY+" = ? ",
    			new String[]{jornada.toString()});
	}
	
	protected void execute()//doInBackground(String... params) 
	{
		try
		{
			// checkejem per connectivitat
			ConnectivityManager cm = (ConnectivityManager) service.getSystemService(Context.CONNECTIVITY_SERVICE);
			boolean online = cm.getActiveNetworkInfo().isConnectedOrConnecting();

			if( !online )
				throw new ConnectivityException();
			
			// cridem per parsejar partits de la jornada
			executeDayMatches();

			// position 1 = bases (b1,b2,b3)
			execute(1);
			// position 2 = aleros (a4,a5,a6,a7)
			execute(2);
			// position 3 = pivots (p8,p9,p10,p11)
			execute(3);
			
			// parsejat ok
	        status = Supermanager.MARKET_PARSED_OK;
	        Log.d(TAG, "MArketSync status: MARKET_PARSED_OK - "+status);
	        return;
		}
		catch(ConnectivityException ce){
			// error de connectivitat
			status = Supermanager.CONNECTIVITY_ERROR_STATUS;
	        Log.d(TAG, "MArketSync status: CONNECTIVITY_ERROR_STATUS - "+status);
			return;
		}
		catch(Exception e){
			// altre error, notifiquem i anem offline
			status = Supermanager.OTHER_ERROR_STATUS;
	        Log.d(TAG, "MArketSync status: OTHER_ERROR_STATUS - "+status);
			return;
		}
	}
	
	/**
	 * Just makes a POST request to create new team and have it on session
	 * for ongoing requests at market pages.
	 * @throws ConnectivityException
	 * @throws Exception
	 */
	/*private void executeNewTeam()
		throws Exception
	{
		// creem post amb vars per crear new team fake
		HttpPost httpPost = new HttpPost(NEWTEAM_POST);
		 // Les dades
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("nombre", Supermanager.NEW_TEAM_NAME));
        nameValuePairs.add(new BasicNameValuePair("CMD", "1"));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		client.execute(httpPost);
	}*/
	
	private void executeDayMatches()
		throws Exception
	{
		HttpGet plHttpGet = new HttpGet(DAYMATCHES_GET);
		HttpResponse response = client.execute(plHttpGet);
		
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		response.getEntity().writeTo(os);
		String dayMatchesPage = os.toString(HTTP.ISO_8859_1);
		
		DayMatchesParser dayMatchesParser = new DayMatchesParser();
		this.dayMatches = dayMatchesParser.parse(dayMatchesPage, jornada);
	}
	
	/*private void executeGetPlayerId(String position) 
		throws Exception
	{
		HttpGet plHttpGet = new HttpGet(MARKET_NEWTEAM_GET+"?posicion="+position);
		HttpResponse response = client.execute(plHttpGet);
		
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		response.getEntity().writeTo(os);
		String marketPage = os.toString(HTTP.ISO_8859_1);
		
		MarketBuyParser marketBuyParser = new MarketBuyParser();
		ArrayList<Player> players = marketBuyParser.parse(marketPage, jornada);
		
		// if closed changes players will be null, no HTML to parse with players
		if( players == null )
			return;
		
		// recorrem players trobats i construim el array necessari aqui
		for (Player player : players) 
		{
			// guardar a hash per despres tenir-lo a tir al crear el Player
			this.idJugPerCodi.put(player.getCodi(), player.getId());
		}
	}*/
	
	/**
	 * Parse market on buy get action, to get shown (by omission) and color.
	 * @param idequ
	 * @param position
	 * @param jornada
	 */
	public void executeBuyMarket(String idequ, String aPosition)
	{
		try
		{
			// checkejem per connectivitat
			ConnectivityManager cm = (ConnectivityManager) service.getSystemService(Context.CONNECTIVITY_SERVICE);
			boolean online = cm.getActiveNetworkInfo().isConnectedOrConnecting();
			
			if( !online )
				throw new ConnectivityException();
			
			// guardem a instancia per el post execute
			position = aPosition;
			
			// fem peticio previa a nuevoequipo pq posi la cookie de ID_EQU
			HttpGet nuevoEquipoGet = new HttpGet(NEW_TEAM_GET);
			HttpResponse nuevoEquipoResponse = client.execute(nuevoEquipoGet);
			ByteArrayOutputStream nuevoEquipoOs = new ByteArrayOutputStream();
			nuevoEquipoResponse.getEntity().writeTo(nuevoEquipoOs);
	        String nuevoEquipoPage = nuevoEquipoOs.toString(HTTP.ISO_8859_1);
			
			String params = (idequ==null)?"posicion="+position:"id_equ="+idequ+"&posicion="+position;
			
			HttpGet httpGet = new HttpGet(MARKET_BUY_GET+"?"+params);
	        HttpResponse response = client.execute(httpGet);
			ByteArrayOutputStream os = new ByteArrayOutputStream();
	        response.getEntity().writeTo(os);
	        String buyMarketPage = os.toString(HTTP.ISO_8859_1);

	        //TODO: revisar q el buy market torna la pagina q toca
	        //Log.d(TAG, "buyMarket:\n"+buyMarketPage+"\n");
	        
	        MarketBuyParser marketBuyParser = new MarketBuyParser();
	        players = marketBuyParser.parse(buyMarketPage, jornada);
	        
	        status = Supermanager.MARKET_BUY_OK;
	        Log.d(TAG, "MarketSync status: MARKET_BUY_OK - "+status);
	        return;
		}
		catch(ConnectivityException ce){
			// error de connectivitat
			status = Supermanager.CONNECTIVITY_ERROR_STATUS;
	        Log.d(TAG, "MarketSync status: CONNECTIVITY_ERROR_STATUS - "+status);
			return;
		}
		catch(Exception e){
			// altre error, notifiquem i anem offline
			status = Supermanager.OTHER_ERROR_STATUS;
	        Log.d(TAG, "MarketSync status: OTHER_ERROR_STATUS - "+status);
			return;
		}
	}	
	
	@SuppressWarnings("rawtypes")
	private void execute(int position)
		throws Exception
	{
		HttpGet plHttpGet = new HttpGet(MARKET_GET+"?id_pos="+position);
		HttpResponse response = client.execute(plHttpGet);
		HtmlCleaner cleaner = new HtmlCleaner();

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		response.getEntity().writeTo(os);
		String marketPage = os.toString(HTTP.ISO_8859_1);
		TagNode node = cleaner.clean(marketPage);

		NumberFormat nf = NumberFormat.getInstance(new Locale("es","ES"));

		// cerquem les jugadors
		Object[] table = node.evaluateXPath(PLAYERS_XPATH);
		TagNode tagTable = (TagNode)table[0];
		TagNode tagTbody = tagTable.getChildTags()[0];
		// llistem els jugados, diferents trs
		int i=0;
		for(Object objTr: tagTbody.getChildren())
		{
			// descartem dos primers tr dels headers
			if( i++ < 2 )
				continue;

			// els tds
			List tds = ((TagNode)objTr).getChildren();

			// inicialitzem player
			Player p = new Player();
			
			// setejem la jornada
			p.setDay(jornada);

			try
			{
				// segon td, status
				TagNode td1 = (TagNode) tds.toArray()[1];
				for (Object td1Child : td1.getChildren()) {
					TagNode img = (TagNode) td1Child;
					if ("img".equals(img.getName())) {
						String src = img.getAttributeByName("src");
						if ("gif/lesion.gif".equals(src))
							p.setStatus("lesio.png");
						if ("gif/baja.gif".equals(src))
							p.setStatus("baixa.png");

						break;
					}
				}

				// tercer td, nationality
				TagNode td2 = (TagNode) tds.toArray()[2];
				for (Object td2Child : td2.getChildren()) {
					TagNode img = (TagNode) td2Child;
					if ("img".equals(img.getName())) {
						String src = img.getAttributeByName("src");
						String nacionality = src.split("/")[1];
						String filename = nacionality.split("\\.")[0];
						p.setNacionality(filename+".png");
						break;
					}
				}

				// quart td, player name
				TagNode td3 = (TagNode) tds.toArray()[3];
				for (Object td3Child : td3.getChildren()) 
				{
					TagNode font = (TagNode) td3Child;
					if ("font".equals(font.getName())) 
					{
						for (Object fontChild : font.getChildren()) {
							if (fontChild instanceof ContentNode) {
								String name = fontChild.toString();
								p.setName(name);
								p.setCodi(name);
								
								Log.d(TAG, "MarketSync parsing code player: " + name
										+ ", jornada: " + jornada);

								break;
							}
						}
						break;
					}
				}

				// cinque td, info
				TagNode td4 = (TagNode) tds.toArray()[4];
				for (Object td4Child : td4.getChildren()) {
					// saltem espais inicials
					if (td4Child instanceof ContentNode)
						continue;

					TagNode a = (TagNode) td4Child;
					if ("a".equals(a.getName())) {
						String on = a.getAttributeByName("onMouseover");
						String info = on.replace("ddrivetip('", "").replace(
								"')", "");
						p.setInfo(info);

						break;
					}
				}

				// sise td, team
				TagNode td5 = (TagNode) tds.toArray()[5];
				for (Object td5Child : td5.getChildren()) {
					if (td5Child instanceof ContentNode) {
						String team = td5Child.toString().trim();
						p.setTeam(team);
						break;
					}
				}

				// sete td, balance
				/*TagNode td6 = (TagNode) tds.toArray()[6];
				for (Object td6Child : td6.getChildren()) {
					if (td6Child instanceof ContentNode) {
						String balance = td6Child.toString().trim();
						p.setBalance(balance);
						break;
					}
				}*/

				// sete td, promedio
				TagNode td6 = (TagNode) tds.toArray()[6];
				for (Object td6Child : td6.getChildren()) {
					if (td6Child instanceof ContentNode) {
						Float average;
						try {
							average = Float.valueOf(nf.parse(
									td6Child.toString().trim()).floatValue());
						} catch (ParseException pe) {
							average = Float.valueOf("0");
						}

						p.setAverage(average);
						break;
					}
				}

				// vuite td, preu
				TagNode td7 = (TagNode) tds.toArray()[7];
				for (Object td7Child : td7.getChildren()) {
					if (td7Child instanceof ContentNode) {
						Integer price;
						try {
							price = Integer.valueOf(nf.parse(
									td7Child.toString().trim()).intValue());
						} catch (ParseException pe) {
							price = Integer.valueOf(0);
						}
						p.setPrice(price);
						break;
					}
				}

				// nove td, minutes
				TagNode td8 = (TagNode) tds.toArray()[8];
				for (Object td8Child : td8.getChildren()) {
					if (td8Child instanceof ContentNode) {
						String minutes = td8Child.toString().trim();
						p.setMinutes(minutes);
						break;
					}
				}

				// dese td, valoracio ultima jornada
				TagNode td9 = (TagNode) tds.toArray()[9];
				for (Object td9Child : td9.getChildren()) {
					if (td9Child instanceof ContentNode) {
						Float rating;
						try {
							rating = Float.valueOf(nf.parse(
									td9Child.toString().trim()).floatValue());
						} catch (ParseException pe) {
							rating = Float.valueOf("0");
						}
						p.setRating(rating);
						break;
					}
				}

				// onze td, mitja valoracioi 3 ultims partits
				TagNode td10 = (TagNode) tds.toArray()[10];
				for (Object td10Child : td10.getChildren()) {
					if (td10Child instanceof ContentNode) {
						Float ratingLast3Games;
						try {
							ratingLast3Games = Float.valueOf(nf.parse(
									td10Child.toString().trim()).floatValue());
						} catch (ParseException pe) {
							ratingLast3Games = Float.valueOf("0");
						}
						p.setRatingLast3Games(ratingLast3Games);
						break;
					}
				}

				// dotze td, puja 15%
				TagNode td11 = (TagNode) tds.toArray()[11];
				for (Object td11Child : td11.getChildren()) {
					if (td11Child instanceof ContentNode) {
						Float increase15;
						try {
							increase15 = Float.valueOf(nf.parse(
									td11Child.toString().trim()).floatValue());
						} catch (ParseException pe) {
							increase15 = Float.valueOf("0");
						}
						p.setIncrease15(increase15);
						break;
					}
				}

				// tretze td, mante preu
				TagNode td12 = (TagNode) tds.toArray()[12];
				for (Object td12Child : td12.getChildren()) {
					if (td12Child instanceof ContentNode) {
						Float keepPrice;
						try {
							keepPrice = Float.valueOf(nf.parse(
									td12Child.toString().trim()).floatValue());
						} catch (ParseException pe) {
							keepPrice = Float.valueOf("0");
						}
						p.setKeepPrice(keepPrice);
						break;
					}
				}

				// catorze td, baixa 15%
				TagNode td13 = (TagNode) tds.toArray()[13];
				for (Object td13Child : td13.getChildren()) {
					if (td13Child instanceof ContentNode) {
						Float decrease15;
						try {
							decrease15 = Float.valueOf(nf.parse(
									td13Child.toString().trim()).floatValue());
						} catch (ParseException pe) {
							decrease15 = Float.valueOf("0");
						}
						p.setDecrease15(decrease15);
						break;
					}
				}

			}catch(Exception e){
				Log.d(TAG, "Error...");
			}

			switch(position)
			{
			case 1:
				p.setPosition(Supermanager.GUARD_POSITION);
				// guardem el player al llistat
				this.guards.add(p);
				break;
			case 2:
				p.setPosition(Supermanager.FORWARD_POSITION);
				// guardem el player al llistat
				this.forwards.add(p);
				break;
			case 3:
			default:
				p.setPosition(Supermanager.CENTER_POSITION);
				// guardem el player al llistat
				this.centers.add(p);
				break;
			}
		}
    }
	
	/**
	 * Guardar les dades trobades a DB.
	 * @throws ClosedChangesException 
	 */
    protected void onPostExecute(Uri uri) throws ClosedChangesException 
    {
    	// tractem cada jugador, bases
    	Log.d(TAG,"Parsed "+guards.size()+" guard players, going to insert");
    	for(Player p: this.guards)
    	{
    		// cerquem position a guardar
    		//p.setPosition(getPosition(position));
    		
    		// update el player al market
    		updatePlayer(uri, p, Supermanager.GUARD_POSITION);
    	}
    	
    	// tractem cada jugador, alers
    	Log.d(TAG,"Parsed "+forwards.size()+" forward players, going to insert");
    	for(Player p: this.forwards)
    	{
    		// cerquem position a guardar
    		//p.setPosition(getPosition(position));
    		
    		// update el player al market
    		updatePlayer(uri, p, Supermanager.FORWARD_POSITION);
    	}
    	
    	// tractem cada jugador, pivots
    	Log.d(TAG,"Parsed "+centers.size()+" center players, going to insert");
    	for(Player p: this.centers)
    	{
    		// cerquem position a guardar
    		//p.setPosition(getPosition(position));
    		
    		// update el player al market
    		updatePlayer(uri, p, Supermanager.CENTER_POSITION);
    	}	
    }
    
    /**
	 * Guardar les dades trobades a DB, update dels players q poden.
	 */
    protected void onMarketBuyPostExecute(Uri uri)
    {
    	// no players parsed...
    	if( players == null )
    	{
    		Log.d(TAG,"MarketSync onMarketBuyPostExecute parserd 0 players, nothing to update");
    		return;
    	}
    	
    	// update per posar el showInBuy a false de tots inicialment
    	ContentValues resetShownValues = new ContentValues(); 
    	resetShownValues.put(Supermanager.Market.SHOWN_IN_BUY, 0);
    	
    	// update nomes
		if( service.getContentResolver().update(Supermanager.Market.CONTENT_URI, 
				resetShownValues, 
				Supermanager.Market.DAY+" = ? ", 
				new String[]{jornada.toString()}) == 0 )
		{
			return;
		}
		
    	Log.d(TAG,"MarketSync onMarketBuyPostExecute parserd "+players.size()+" players, going to update");
    	for(Player p: this.players)
    	{
    		// afegim el position
    		p.setPosition(getPosition(position));
    		
    		// update el player al market
    		if( !insertOrUpdateBuyPlayer(uri, p) )
    			Log.d(TAG,"MarketSync onMarketBuyPostExecute error updating players: "+p.getId()+" on day: "+p.getDay());
    	}
    }
    
    /**
     * convert a1 -> GUARDS, and so on...
     * @param playerPosition
     * @return
     */
    private String getPosition(String playerPosition)
    {
    	if( playerPosition.startsWith("b"))
    		return Supermanager.GUARD_POSITION;
    	if( playerPosition.startsWith("a"))
    		return Supermanager.FORWARD_POSITION;
    	if( playerPosition.startsWith("p"))
    		return Supermanager.CENTER_POSITION;
    	
    	// per defecte tornem base
    	return Supermanager.GUARD_POSITION;
    }
    
    /**
     * Update buy market data, when called from team detail on buy player.
     * @param uri
     * @param p
     * @return
     */
    private boolean insertOrUpdateBuyPlayer(Uri uri, Player p)
    {
    	Log.d(TAG,"MarketSync.updateBuyPlayer player id: "+p.getId());
    	
    	// insertem player
		ContentValues values = new ContentValues();
		values.put(Supermanager.Market.SHOWN_IN_BUY, 1);
		values.put(Supermanager.Market.COLOR_IN_BUY, p.getColorInBuy());
		
		Uri playerUri = Supermanager.Market.CONTENT_URI;
		
		// si idjug es numeric update per ID_PLAYER, altrament per CODI_PLAYER
		// ja que venim de buy i no son jugadors comprables
		String selection = Supermanager.Market.CODI_PLAYER+" = ? AND "+
			Supermanager.Market.DAY+" = ? ";
		try{
			Integer.parseInt(p.getId());
			selection = Supermanager.Market.ID_PLAYER+" = ? AND "+
				Supermanager.Market.DAY+" = ? ";
		}catch(NumberFormatException nfe){}
		
		// update nomes, pero amb el codi, pq el id_jug els q no son comprables no
		// el tenim, no esta al html parsejat
		if( service.getContentResolver().update(Supermanager.Market.CONTENT_URI, 
				values, 
				selection, 
				new String[]{p.getId(),p.getDay().toString()}) == 0 )
		{
			// altrement fem insert amb camps necessaris per l'insert!
			// aqui tenim tots els camps donat q es un nuevoequipo i 
			// inicialment es poden comprat tots, sempre tindrem idjug
			values.put(Supermanager.Market.ID_PLAYER, p.getId());
			values.put(Supermanager.Market.POSITION, p.getPosition());
			values.put(Supermanager.Market.BALANCE, "");
			values.put(Supermanager.Market.DAY, p.getDay());
			values.put(Supermanager.Market.STATUS, p.getStatus());
			values.put(Supermanager.Market.NACIONALITY, p.getNacionality());
			values.put(Supermanager.Market.NAME, p.getName());
			values.put(Supermanager.Market.CODI_PLAYER, p.getCodi());
			values.put(Supermanager.Market.TEAM, p.getTeam());
			values.put(Supermanager.Market.INFO, "");
			values.put(Supermanager.Market.VS_TEAM, "");
			values.put(Supermanager.Market.AVERAGE, 0f);
			values.put(Supermanager.Market.PRICE, 0);
			values.put(Supermanager.Market.MINUTES, "");
			values.put(Supermanager.Market.RATING, 0f);
			values.put(Supermanager.Market.RATING_LAST3_GAMES, 0f);
			values.put(Supermanager.Market.INCREASE_15, 0f);
			values.put(Supermanager.Market.KEEP_PRICE, 0f);
			values.put(Supermanager.Market.DECREASE_15, 0f);
			
			playerUri = service.getContentResolver().insert(uri, values);
			String lastPathSegment = playerUri.getLastPathSegment();
			Log.d(TAG, "Market inserting player with codi jug [" + p.getCodi()
					+ "] with Uri [" + playerUri + "] lastPathSegment ["
					+ lastPathSegment + "]");
			return true;
		}
		
		return true;
    }
    
    /**
	 * Insert or Update Player as needed.
	 * @param uri
	 * @param pl
	 * @return
     * @throws ClosedChangesException 
	 */
	private String updatePlayer(Uri uri, Player p, String position) 
		throws ClosedChangesException
	{
		// com al market no tenim idjug ni codi com a ACB, passem 
		// com a codi el nom del jugador
		//p.setCodi(this.idJugPerCodi.get(p.getCodi()));
		
		// setejem el vs_team parsejat per la jornada
		p.setVsTeam(this.dayMatches.get(p.getTeam()));
		
		// insertem player
		ContentValues values = new ContentValues();
		//values.put(Supermanager.Market.CODI_PLAYER, p.getCodi());
		
		values.put(Supermanager.Market.POSITION, position);
		values.put(Supermanager.Market.DAY, p.getDay());
		values.put(Supermanager.Market.STATUS, p.getStatus());
		values.put(Supermanager.Market.NACIONALITY, p.getNacionality());
		values.put(Supermanager.Market.NAME, p.getName());
		values.put(Supermanager.Market.BALANCE, "");
		values.put(Supermanager.Market.INFO, p.getInfo());
		values.put(Supermanager.Market.TEAM, p.getTeam());
		values.put(Supermanager.Market.VS_TEAM, p.getVsTeam());
		values.put(Supermanager.Market.AVERAGE, p.getAverage());
		values.put(Supermanager.Market.PRICE, p.getPrice());
		values.put(Supermanager.Market.MINUTES, p.getMinutes());
		values.put(Supermanager.Market.RATING, p.getRating());
		values.put(Supermanager.Market.RATING_LAST3_GAMES, p.getRatingLast3Games());
		values.put(Supermanager.Market.INCREASE_15, p.getIncrease15());
		values.put(Supermanager.Market.KEEP_PRICE, p.getKeepPrice());
		values.put(Supermanager.Market.DECREASE_15, p.getDecrease15());
		values.put(Supermanager.Market.SHOWN_IN_BUY, 0);
		values.put(Supermanager.Market.COLOR_IN_BUY, (String)null);
		
		String lastPathSegment = "0";
		
		Log.d(TAG, "Market update codi: "+p.getCodi()+", id: " + p.getId() + ", day: "
				+ p.getDay().toString());
		
		// si update no retorna 1 reg, llavors error... hi ha de ser! hem fet abans marketBuyParse!
		if (service.getContentResolver().update(
				uri,
				values,
				Supermanager.Market.CODI_PLAYER + " = ? AND "
						+ Supermanager.Market.DAY + " = ? ",
				new String[] { p.getCodi(), p.getDay().toString() }) == 0) {
			
			// altrement intentem fer insert...
			Log.d(TAG, "Market update player with codi jug ["+p.getCodi()+"] and day["+p.getDay().toString()+"] "+
					"not found, going to insert...");
			
			// cerquem el id del jugador de jornades previes...
			String playerId = getPlayerIdByCodi(p.getCodi());
			values.put(Supermanager.Market.ID_PLAYER, playerId);
			values.put(Supermanager.Market.CODI_PLAYER, p.getCodi());
			
			Uri playerUri = service.getContentResolver().insert(Supermanager.Market.CONTENT_URI, values);
			
			lastPathSegment = playerUri.getLastPathSegment();
			Log.d(TAG, "Market inserting player with codi jug [" + p.getCodi()
					+ "] idplayer [" + playerId + "] with Uri [" + playerUri + "] lastPathSegment ["
					+ lastPathSegment + "]");
		} 

		return lastPathSegment;
	}
	
	// recuperem el player_id d'alguna jornada anterior donat el codi del player.
	private String getPlayerIdByCodi(String codi)
	{
		String playerId = null;
		
		Cursor cursor = service.getContentResolver().query(Supermanager.Market.CONTENT_URI, 
			new String[]{Supermanager.Market.ID_PLAYER}, 
			Supermanager.Market.CODI_PLAYER+" = ? ", 
			new String[]{codi}, 
			Supermanager.Market.DAY+" DESC");
		
		// agafem la primera descendentment per jornada que trobem,
		// si no se'n troba cap tornara null
		if(	cursor.moveToFirst() )
		{
			playerId = cursor.getString(0);
		}
		
		// tanquem el cursor
		cursor.close();
		
		return playerId;
	}
}	
